package com.qf.cx.simplenms.persist.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.qf.cx.simplenms.persist.dao.api.ReaderGroupDao;
import com.qf.cx.simplenms.persist.entity.ReaderGroupEntity;

@Repository
public class ReaderGroupDaoImpl implements ReaderGroupDao {
	@Autowired
	@Qualifier("hibernateSessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void addReaderGroup(ReaderGroupEntity readerGroup) {
		Session session = sessionFactory.getCurrentSession();
		session.save(readerGroup);
	}

	@Override
	public void deleteReaderGroup(String name) {
		Session session = sessionFactory.getCurrentSession();
		ReaderGroupEntity readerGroup = session.get(ReaderGroupEntity.class, name);
		if (readerGroup != null) {
			session.delete(readerGroup);
		}
	}

	@Override
	public void updateReaderGroup(ReaderGroupEntity readerGroup) {

		Session session = sessionFactory.getCurrentSession();
		ReaderGroupEntity sessionObject = session.get(ReaderGroupEntity.class, readerGroup.getName());
		if (sessionObject == null) {
			session.save(readerGroup);
			return;
		}
		sessionObject.setAntennaEntities(readerGroup.getAntennaEntities());
		session.update(sessionObject);
	}

	@Override
	public ReaderGroupEntity getReaderGroup(String name) {
		Session session = sessionFactory.getCurrentSession();
		ReaderGroupEntity readerGroup = session.get(ReaderGroupEntity.class, name);
		return readerGroup;
	}

	@Override
	public List<ReaderGroupEntity> getReaderGroups() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from ReaderGroupEntity");
		List<ReaderGroupEntity> resultList = query.list();
		return resultList;
	}

}
